package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.ArticleOperationMessage;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author GQ
 * @since 2022-08-07
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.hotArticleScoreTopic}")
    private String hotArticleScoreTopic;

    /**
     * 保存点赞记录，将点赞数据存入Redis缓存
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveLikes(LikesBehaviorDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(401, "请登录后操作！");
        }
//       构建点赞Key
        String redisKey = "leadnews:article:like:" + dto.getArticleId();
        if (dto.getOperation() == 0) {
            redisTemplate.opsForSet().add(redisKey, user.getUserId().toString());
        } else {
            redisTemplate.opsForSet().remove(redisKey, user.getUserId().toString());
        }
        //TODO 将点赞行为 发送到Kafka话题中
        ArticleOperationMessage operationMessage = new ArticleOperationMessage();
        operationMessage.setArticleId(dto.getArticleId());
        operationMessage.setType(1);
        operationMessage.setAdd(dto.getOperation() == 0 ? 1 : -1);
        kafkaTemplate.send(hotArticleScoreTopic, JSON.toJSONString(operationMessage));
        return ResponseResult.okResult();
    }
}
